package com.star.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.star.search.pojo.SkuInfo;
import com.star.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

*/
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    /**
     * 按条件分页查询
     * @param searchMap
     * @return
     */
    @Override
    public Map search(Map<String, String> searchMap) {
        Map<String, Object> resultMap = new HashMap<>();
        //构建查询
        if (searchMap != null) {
            //开启查询
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //规格过滤查询
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")) {
                    //获取规格开头的数据
                    String value = searchMap.get(key).replace("%2B","+");
                    /**
                     * key=spec_尺寸
                     * 指定字段为specMap.尺寸.keyword
                     */
                    boolQuery.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }
            //价格区间过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))) {
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2) {
                    //小于等于
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                //大于等于
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));

            }
            //品牌聚合查询
            String skuBrand = "skuBrand";
            //聚合条件设置
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
            //规格信息聚合查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));


            //分页查询
            //当前页
            String pageNum = searchMap.get("pageNum");
            //每页显示条数
            String pageSize = searchMap.get("pageSize");

            //如果前端未传递参数，设置默认数
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";

            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //设置分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));


            //按照相关字段排序查询
            //操作的字段  排序方式 升asc 降序desc
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                } else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮字段
                    .preTags("<span style='color:red'>")    //设置前缀
                    .postTags("</span>");

            nativeSearchQueryBuilder.withHighlightFields(field);



            nativeSearchQueryBuilder.withQuery(boolQuery);
            /**
             * 参数：
             * 1.条件构建对象
             * 2.操作实体类
             * 3.查询结果对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //查询结果操作
                    List<T> list=new ArrayList<>();
                    //获取命中结果数据
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        //有结果
                        for (SearchHit hit : hits) {
                            String sourceAsString = hit.getSourceAsString();
                            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                //有高亮字段,替换为高亮字段
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }
                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //封装结果
            //封装总记录数
            resultMap.put("total", resultInfo.getTotalElements());
            //封装总页数
            resultMap.put("totalPages", resultInfo.getTotalPages());
            //数据集合
            resultMap.put("rows", resultInfo.getContent());
            //封装品牌聚合分组结果
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);

            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);
            //封装规格聚合结果
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);

            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", this.formatSpec(specList));

            resultMap.put("pageNum", pageNum);
            return resultMap;
        }
        return null;
    }

    /**
     * 原有数据
     *  [
     *         "{'颜色': '黑色', '尺码': '平光防蓝光-无度数电脑手机护目镜'}",
     *         "{'颜色': '红色', '尺码': '150度'}",
     *         "{'颜色': '黑色', '尺码': '150度'}",
     *         "{'颜色': '黑色'}",
     *         "{'颜色': '红色', '尺码': '100度'}",
     *         "{'颜色': '红色', '尺码': '250度'}",
     *         "{'颜色': '红色', '尺码': '350度'}",
     *         "{'颜色': '黑色', '尺码': '200度'}",
     *         "{'颜色': '黑色', '尺码': '250度'}"
     *     ]
     *
     *    需要的数据格式
     *    {
     *        颜色:[黑色,红色],
     *        尺码:[100度,150度]
     *    }
     */
    //转换规格数据格式
    public Map<String, Set<String>> formatSpec(List<String> specList) {
        Map<String, Set<String>> resultMap = new HashMap<>();
        if (specList != null && specList.size() > 0) {
            //list中有数据 遍历取出value
            for (String specJSON : specList) {
                //将JSON转换为map集合
                Map<String,String> specMap = JSON.parseObject(specJSON, Map.class);
                //遍历集合
                for (String specKey : specMap.keySet()) {
                    //判断Set中是否存在
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet == null) {
                        //不存在  声明
                        specSet = new HashSet<>();
                    }
                    //将规格数据存入Set集合
                    specSet.add(specMap.get(specKey));
                    //将set放入map
                    resultMap.put(specKey, specSet);
                }

            }
        }
        return resultMap;
    }
}
